/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import dao.UsuarioDAO;
import entity.Usuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.MD5;

/**
 *
 * @author User
 */
@WebServlet(name = "ControladoraUsuario", urlPatterns = {"/ControladoraUsuario"})
public class ControladoraUsuario extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException, ParseException {

        String action = request.getParameter("action");

        if (action.equals("inserir")) {
        
            String nome = request.getParameter("campoNome");
            String cargo = request.getParameter("cargo");
            String matricula = request.getParameter("campoMat");            
            String email = request.getParameter("campoEmail");
            String login = request.getParameter("campoLogin");
            String senha = request.getParameter("campoSenha");
            
            MD5 md5 = new MD5();
            String senhacrip = md5.ConvertMD5(senha);
            
            Usuario usuario = new Usuario();
            usuario.setNome(nome);
            usuario.setCargo(cargo);
            usuario.setNumMat(matricula);
            usuario.setEmail(email);
            usuario.setLogin(login);
            usuario.setSenha(senhacrip);



            UsuarioDAO dao = new UsuarioDAO();
            
            if (dao.matExistente(matricula)){
                
            request.setAttribute("mensagemMat","Matrícula já cadastrada");  
            RequestDispatcher rd = request.getRequestDispatcher("/cadastra_usuario.jsp");
            rd.forward(request, response);         
            }
            
            if (dao.loginExistente(login)){
                
            request.setAttribute("mensagemLogin","Login já cadastrado");  
            RequestDispatcher rd = request.getRequestDispatcher("/cadastra_usuario.jsp");
            rd.forward(request, response);    
                
            }            
            
            
            dao.insere(usuario);

            RequestDispatcher rd = getServletContext().getRequestDispatcher("/buscar_usuario.jsp");
            rd.forward(request, response);
            
        }  

        else if (action.equals("deletar")){

        int iduser = Integer.parseInt(request.getParameter("id"));
       
        Usuario usuario = new Usuario();
        usuario.setIdUsuario(iduser);
            
        UsuarioDAO DAO = new UsuarioDAO();
        DAO.excluir(usuario);
        
        RequestDispatcher rd = getServletContext().getRequestDispatcher("/buscar_usuario.jsp");
        rd.forward(request, response);
        }
        
        else if (action.equals("visualizar")) {

            String id = request.getParameter("id");
            int num = 0;
            num = Integer.parseInt(id);
            Usuario usuario = new Usuario();
            UsuarioDAO dao = new UsuarioDAO();
            usuario = dao.buscar_usuario(num);
            request.setAttribute("usuario", usuario);
            RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/detalhes_usuario.jsp");
            rd.forward(request, response);   
            
        }  else if (action.equals("pesquisar")){            
            String pesquisa = request.getParameter("busca_usuario");                                          
            UsuarioDAO daousuario = new UsuarioDAO();
            List<Usuario> usuario = daousuario.procurar(pesquisa);            
            request.setAttribute("usuario", usuario);
            RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/buscar_usuario_listados.jsp");
            rd.forward(request, response);
        } else {
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/buscar_usuario.jsp");
            rd.forward(request, response);
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ControladoraUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(ControladoraUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(ControladoraUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(ControladoraUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
